from flask import Blueprint, request, current_app
import urllib
import urlparse
import os
import pymysql
import json
import time

from .db import get_db

app = current_app

data_upload = Blueprint("data_upload", __name__)

@data_upload.route("/info", methods=["GET", "POST"])
def info():

    if request.method == "GET":
        return "ok"

    d2 = request.get_json(force = True, cache = False)

    app.logger.debug("receive data: %s" % (str(d2), ))

    userinfo=d2["userInfo"]
    statis = d2["statisticsInfo"]

    if not userinfo.has_key("terminalId"):
        return "400 missing some key", 400

    tmp_ui = {}
    tmp_st = {}

    for k,v in userinfo.items():
        if isinstance(v, str) or isinstance(v, unicode):
            v = pymysql.escape_string(v)

        tmp_ui[k] = v

    for k,v in statis.items():
        if isinstance(v, str) or isinstance(v, unicode):
            v = pymysql.escape_string(v)

        tmp_st[k] = v

    userinfo = tmp_ui
    statis = tmp_st

    if not statis.has_key("baiduLiveness"):
        statis["baiduLiveness"] = 0

    if not statis.has_key("musicDuration"):
        statis["musicDuration"] = 0

    if not statis.has_key("openByOther"):
        statis["openByOther"] = 0

    if not userinfo.has_key("deviceId"):
        userinfo["deviceId"] = ""

    if len(userinfo["deviceId"]) != len("3050001107"):
        userinfo["deviceId"] = ""
        userinfo["firmwareVersion"] = ""

    if not userinfo.has_key("baiduAccount"):
        userinfo["baiduAccount"] = ""

    if not userinfo.has_key("storageTotal"):
        userinfo["storageTotal"] = 0

    if not userinfo.has_key("storageFree"):
        userinfo["storageFree"] = 0

    is_test = int(d2.get("test", 0))

    if is_test:
        user_tbl = u"t_userinfo"
        mtime_tbl = u"t_mediatimes"
        mname_tbl = u"t_movienames"
    else:
        user_tbl = u"userinfo"
        mtime_tbl = u"mediatimes"
        mname_tbl = u"movienames"

    #conn = db.connect()
    conn = get_db()
    cur = conn.cursor()
    sql = u"""select id from {user_tbl}
    where
        terminalid='{terminalId}'
        and deviceid='{deviceId}'
    """
    s = sql.format(user_tbl=user_tbl, **userinfo)
    #print s
    cur.execute(s)
    rs = cur.fetchall()
    n_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))

    userinfo["last_update"] = n_time
    statis["last_update"] = n_time

    # no record
    if len(rs) == 0:
        sql = u"""insert into {user_tbl} (terminalid, deviceid, terminaltype,terminalversion,clientversion,
                firmwareversion,baiduaccount,last_update,createdate, storagetotal, storagefree
                )
               values(
                    '{terminalId}','{deviceId}','{terminalType}','{terminalVersion}','{clientVersion}',
                    '{firmwareVersion}','{baiduAccount}','{last_update}','{createdate}', {storageTotal}, {storageFree}
                    )
                    """
        s = sql.format(user_tbl = user_tbl, createdate=n_time, **userinfo)
        #print s
        cur.execute(s)
        conn.commit()
    else:
        # has record, check if version is changed
        sql = u"""select id from {user_tbl}
        where
            terminalid='{terminalId}'
            and deviceid = '{deviceId}'
            and terminalversion='{terminalVersion}'
            and clientversion = '{clientVersion}'
            and firmwareversion='{firmwareVersion}'
            and baiduaccount = '{baiduAccount}'
        """
        s = sql.format(user_tbl=user_tbl, **userinfo)
        cur.execute(s)
        rs = cur.fetchall()

        # version is changed
        if len(rs) == 0:
            sql = u"""update {user_tbl} set
                terminalversion='{terminalVersion}',
                clientversion='{clientVersion}',
                baiduaccount='{baiduAccount}',
                firmwareversion='{firmwareVersion}',
                last_update='{last_update}'
            where
                terminalid='{terminalId}'
                and deviceid='{deviceId}'
                """
            s = sql.format(user_tbl=user_tbl, **userinfo)
            cur.execute(s)
            conn.commit()


    m=[]
    m_cols=[]
    m_values=[]

    if int(statis["pictureDuration"]):
        m.append("picturetime=picturetime+%d" % (int(statis["pictureDuration"]),))
        #m.append("pictureliveness=pictureliveness+1")
        m_cols.append("picturetime")
        m_values.append("'{pictureDuration}'")

    if int(statis["videoDuration"]):
        m.append("videotime=videotime+%d" % (int(statis["videoDuration"]),))
        #m.append("videoliveness=videoliveness+1")
        m_cols.append("videotime")
        m_values.append("'{videoDuration}'")

    if int(statis["documentDuration"]):
        m.append("documenttime=documenttime+%d" % (int(statis["documentDuration"]),))
        #m.append("documentliveness=documentliveness+1")
        m_cols.append("documenttime")
        m_values.append("'{documentDuration}'")

    if int(statis["startCount"]):
        m.append("startcount=startcount+%d" % (int(statis["startCount"]),))
        #m.append("openliveness=openliveness+1")
        m_cols.append("startcount")
        m_values.append("'{startCount}'")

    if int(statis["musicDuration"]):
        m.append("musictime=musictime+%d" % (int(statis["musicDuration"]),))
        #m.append("musicliveness=musicliveness+1")
        m_cols.append("musictime")
        m_values.append("'{musicDuration}'")

    if int(statis["baiduLiveness"]):
        m.append("baiduliveness=baiduliveness+1")
        m_cols.append("baiduliveness")
        m_values.append("'{baiduLiveness}'")

    if int(statis["openByOther"]):
        m.append("openbyother=openbyother+%d" % (int(statis["openByOther"]),))
        m_cols.append("openbyother")
        m_values.append("'{openByOther}'")

    if m or m_cols:
        r_date = statis["createTime"]
        sql = u"select id from {mtime_tbl} where terminalid='{terminalId}' and recorddate='{r_date}'"
        s = sql.format(mtime_tbl=mtime_tbl, terminalId = userinfo["terminalId"], r_date = r_date)
        cur.execute(s)
        rs = cur.fetchall()
        if len(rs) > 0:
            m.append("last_update='{last_update}'")
            sql = u"update {mtime_tbl} set %s where terminalid='{terminalId}' and recorddate='{r_date}'" % (",".join(m),)
            s = sql.format(mtime_tbl = mtime_tbl, r_date = r_date, **userinfo)
            cur.execute(s)
            conn.commit()
        else:
            m_cols.append("terminalid")
            m_values.append("'{terminalId}'")
            m_cols.append("last_update")
            m_values.append("'{last_update}'")
            m_cols.append("recorddate")
            m_values.append("'{r_date}'")
            sql = u"insert into {mtime_tbl} (%s) values(%s)" % (",".join(m_cols), ",".join(m_values))
            statis["terminalId"] = userinfo["terminalId"]
            s = sql.format(mtime_tbl=mtime_tbl, r_date = r_date, **statis)
            cur.execute(s)
            conn.commit()

    movie_names = statis["videoNames"]
    names = []

    for v in movie_names:
        watch_time = 0
        filesize = 0
        videolength = ""
        resolution = ""
        if isinstance(v, str) or isinstance(v, unicode):
            parsed = urlparse.urlparse(v)
            u1 = urllib.unquote(parsed.path.encode("utf-8"))
            bname = os.path.basename(u1)
        elif isinstance(v, list):
            if len(v) == 2:
                vname, watch_time = v
            elif len(v) == 5:
                vname, watch_time, filesize, videolength, resolution = v
            parsed = urlparse.urlparse(vname)
            u1 = urllib.unquote(parsed.path.encode("utf-8"))
            bname = os.path.basename(u1)
        t2 = (userinfo["terminalId"], bname, n_time, watch_time, filesize, videolength, resolution)
        names.append(t2)

    if names:
        sql = u"insert into {mname_tbl} (terminalid, videoname, watch_time, duration,filesize,videolength, resolution) values(%s, %s, %s, %s, %s, %s, %s)"
        s = sql.format(mname_tbl = mname_tbl)
        cur.executemany(s, names)
        conn.commit()

    cur.close()

    return json.dumps({"time": statis["createTime"]})
